package com.statistic

import android.app.Activity
import android.view.View
import android.view.ViewGroup
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy


/**
 * @describe:
 * @Author: lixiaopeng
 * @Date: 4/9/21
 */
object Statistic {

    private const val TAG = "Statistic"

    fun init() {

    }

    fun start(activity: Activity) {
        val window = activity.window
        val decorView = window.decorView as ViewGroup
        val childCount = decorView.childCount
        if (childCount <= 0) {
            return
        }
        try {
            start(decorView)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun start(viewGroup: ViewGroup) {
        val childCount = viewGroup.childCount
        for (index in 0 until childCount) {
            val childAt = viewGroup.getChildAt(index)
            if (childAt is ViewGroup) {
                start(childAt)
            }
            val setOnClickListener = childAt.javaClass.getMethod("setOnClickListener", View.OnClickListener::class.java)

            val realClick = this.javaClass.getMethod("realClick", View::class.java)

            val handle = ProxyHandle(this, realClick)

            val newProxyInstance = Proxy.newProxyInstance(View.OnClickListener::class.java.classLoader, View.OnClickListener::class.java.interfaces, handle)
            setOnClickListener.invoke(childAt, newProxyInstance)
        }
    }

    class ProxyHandle:InvocationHandler{
        private  val realObj:Any;
        private  val realMethod:Method;

        constructor(realObj: Any, realMethod: Method) {
            this.realObj = realObj
            this.realMethod = realMethod
        }


        override fun invoke(proxy: Any?, method: Method, args: Array<out Any>?): Any {
            if (realObj!=null&&realMethod!=null){
                return realMethod.invoke(realObj, args);
            }else {
                return method.invoke(proxy, args);
            }
        }

    }



    class ProxyHandler() : InvocationHandler {
        override fun invoke(proxy: Any, method: Method?, args: Array<Any>?): Any? {
            println("点击之前")
            return null
        }
    }
}